# -*- coding: utf-8 -*-

import logging
import os
import time
import datetime
import redis

from scrapy.crawler import CrawlerProcess
from django.core.management.base import BaseCommand, CommandError
from scrapy.utils.log import configure_logging
from scrapy.utils.project import get_project_settings

import config
from socar import settings


# python manage.py clear_bbs_running
class Command(BaseCommand):
    help = 'clear bbs running'

    def add_arguments(self, parser):
        parser.add_argument('-a', action = 'append', dest = 'spargs', default = [],
                            help = 'set spider argument (may be repeated)')

    # 必须实现的方法
    def handle(self, *args, **options):
        os.chdir(settings.BASE_DIR)

        redis_db = redis.StrictRedis(**config.redis_config)

        bbs_running = []
        while redis_db.llen('bbs_running') > 0:
            bbs_running.append(redis_db.rpop('bbs_running'))

        redis_db.sadd('bbs', *bbs_running)

        print('time:%s len:%s bbs_running:%s' % (str(datetime.datetime.now()), len(bbs_running), bbs_running))


def arglist_to_dict(arglist):
    """Convert a list of arguments like ['arg1=val1', 'arg2=val2', ...] to a
    dict
    """
    return dict(x.split('=', 1) for x in arglist)
